package hqu.cst.xah.onlinemaill.controller;

import hqu.cst.xah.onlinemaill.pojo.Order;
import hqu.cst.xah.onlinemaill.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/getAllOrders")
    public List<Order> getAllProducts() {
        return orderService.getAllOrders();
    }

    // 删除订单
    @DeleteMapping("/deleteOrder")
    public String deleteOrder(@RequestParam("id") Integer orderId) {
        if (orderId == null) {
            return "订单ID不能为空";
        }

        try {
            boolean isDeleted = orderService.deleteOrder(orderId);
            if (isDeleted) {
                return "订单删除成功";
            } else {
                return "订单删除失败，订单不存在";
            }
        } catch (Exception e) {
            return "删除订单时发生错误：" + e.getMessage();
        }
    }


    // 修改订单
    @PutMapping("/updateOrder")
    public String updateOrder(@RequestParam("orderId") Integer orderId, @RequestBody Order updatedOrder) {
        try {
            boolean isUpdated = orderService.updateOrder(orderId, updatedOrder);
            if (isUpdated) {
                return "订单更新成功";
            } else {
                return "订单更新失败，订单不存在";
            }
        } catch (Exception e) {
            return "更新订单时发生错误：" + e.getMessage();
        }
    }

    // 新建订单
    @PostMapping("/createOrder")
    public String createOrder(@RequestBody Order newOrder) {
        if (newOrder == null) {
            return "订单数据不能为空";
        }

        try {
            boolean isCreated = orderService.createOrder(newOrder);
            if (isCreated) {
                return "订单创建成功";
            } else {
                return "订单创建失败";
            }
        } catch (Exception e) {
            return "创建订单时发生错误：" + e.getMessage();
        }
    }

}
